package com.zranger.locationdevice.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 具体逻辑处理
 *
 * @author kent
 * @date 15-9-2.
 */
@Sharable
public class LocationDeviceServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 接收到包处理方法
     * 具体的逻辑处理放在这个方法中
     *
     * @param ctx
     * @param msg 这个参数就是设备发过来的完整的包
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        //读取包内容
        ByteBuf readBuf = (ByteBuf) msg;
        byte[] bytes = new byte[readBuf.readableBytes()];
        readBuf.readBytes(bytes, 0, readBuf.readableBytes());
        System.out.println("-------------receive a message----------------");
        System.out.println(new String(bytes));

        //返回内容。这里是作为示例随便返回的abcde
        ByteBuf sendBuf = Unpooled.buffer(256);
        sendBuf.writeBytes("abcde".getBytes());
        ctx.writeAndFlush(sendBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}
